﻿using QFramework;
using UnityEngine;

namespace HKTools
{
    public class Test_UseTcpServer : MonoBehaviour, IController
    {
        public IArchitecture GetArchitecture()
        {
            return HK_ArchitectureProvider.Architecture;
        }

        void Start()
        {
            this.RegisterEvent<Event_TCP_ClientConnect>(args =>
            {
                HKDebug.Log($"Event:Client端 {args._address}:{args._port} 加入", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_TCP_ClientDisConnect>(args =>
            {
                HKDebug.Log($"Event:Client端 {args._address}:{args._port} 退出", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            this.RegisterEvent<Event_TCP_FromClientMsg>(args =>
            {
                HKDebug.Log($"Event:Client端 {args._address}:{args._port} 发送消息 {args._msg}", LogColor.Green);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        void OnGUI()
        {
            GUILayout.Space(2);

            if (GUILayout.Button("开启 Server"))
            {
                this.SendCommand(new CMD_TCP_StartServer(8080));
            }

            GUILayout.Space(2);

            if (GUILayout.Button("关闭 Server"))
            {
                this.SendCommand(new CMD_TCP_CloseServer());
            }

            GUILayout.Space(2);

            if (GUILayout.Button("给 Client端 发送消息"))
            {
                this.SendCommand(new CMD_TCP_SendMsgS2C("Hello Client"));
            }
        }

        void OnDestroy()
        {
            this.SendCommand(new CMD_TCP_CloseServer());
        }
    }
}